package com.zjzaki.thingsboard.activity.bluetooth;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.zjzaki.thingsboard.R;
import com.zjzaki.thingsboard.adapter.ListViewBluetoothAdapter;
import com.zjzaki.thingsboard.common.LoadingDialog;
import com.zjzaki.thingsboard.util.BluetoothUtil;
import com.zjzaki.thingsboard.util.PermissionUtil;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class DeviceBluetoothListActivity extends BluetoothBaseActivity implements View.OnClickListener {

    /**
     * 动作栏
     */
    private Toolbar toolbar;
    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout swipeRefreshLayout;
    /**
     * 标签
     */
    private final String TAG = "bluetoothList";
    /**
     * 蓝牙广播接收器
     */
    private BluetoothBroadcastReceiver mBluetoothBroadcastReceiver;
    /**
     * 当前连接的蓝牙设备
     */
    private BluetoothDevice mCurDevice = null;
    /**
     * 状态 0:表示测试中，1：表示成功，-1：表示失败
     */
    private int mFlag = 0;
    /**
     * 设备列表
     */
    private List<BluetoothDevice> deviceList = new LinkedList<>();
    /**
     * rssi列表
     */
    private List<Short> rssiList = new LinkedList<>();
    /**
     * 蓝牙设备适配器
     */
    private ListViewBluetoothAdapter listViewBluetoothAdapter;
    /**
     * 蓝牙适配器
     */
    protected BluetoothAdapter mBluetoothAdapter;
    /**
     * 设备详细弹窗
     */
    private android.app.AlertDialog deviceDialog = null;

    /**
     * 界面创建时
     * @param savedInstanceState 从String键到各种Parcelable值的映射。
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置蓝牙列表页主界面
        setContentView(R.layout.activiity_bluetooth);
        //得到当前应用的上下文对象
        mContext = DeviceBluetoothListActivity.this;
        //得到蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //注册广播
        mBluetoothBroadcastReceiver = new BluetoothBroadcastReceiver();
        //初始化加载动画框
        loadingDialog = new LoadingDialog(mContext);
        //过滤器
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        //开启蓝牙广播
        mContext.registerReceiver(mBluetoothBroadcastReceiver, filter);
        //初始化下拉刷新
        initRefreshLayout();
        //权限申请
        String[] pgList = new String[]{Manifest.permission_group.LOCATION, Manifest.permission_group.STORAGE};
        PermissionUtil.requestByGroupName((Activity) mContext, pgList, 10000, mPermissionsListener);
        //初始化界面
        initView();
    }

    /**
     * 销毁方法
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mContext.unregisterReceiver(mBluetoothBroadcastReceiver);
    }

    /**
     * 初始化界面
     */
    private void initView() {

        //提示栏
//        txtTip = (TextView) findViewById(R.id.txtTip);
//        txtTip.setText("");
//        txtTip.setMovementMethod(ScrollingMovementMethod.getInstance());
        //得到蓝牙设备列表的工具栏
        toolbar = findViewById(R.id.toolbar_bluetooth);
        //设置动作栏
        setSupportActionBar(toolbar);
        ActionBar supportActionBar = getSupportActionBar();
        //设置返回键可见
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        //设置标题
        supportActionBar.setTitle("蓝牙巡检");
        //开始扫描设备
        scanBluetooth();
    }

    /**
     * 返回键状态监听
     * @param item 菜单栏
     * @return true表示单击
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 搜索周边蓝牙
     */
    public void scanBluetooth() {
        if (mBluetoothAdapter == null) {
            showToast("当前设备不支持蓝牙功能！");
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            showToast("当前蓝牙未打开");
            openBluetooth();
            return;
        }
        //显示扫描弹窗
        showScanDialog();
    }

    /**
     * 蓝牙搜索对话框初始化及显示
     */
    @SuppressLint("MissingPermission")
    private void showScanDialog() {

        LayoutInflater layoutInflater = LayoutInflater.from(mContext);

        //列表初始化
        ListView listScan = (ListView) findViewById(R.id.listview_bluetooth);
        deviceList.clear();
        rssiList.clear();
        listViewBluetoothAdapter = new ListViewBluetoothAdapter(mContext, deviceList, rssiList);
        listScan.setAdapter(listViewBluetoothAdapter);
        listScan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mCurDevice = deviceList.get(i);
                new Thread() {
                    @Override
                    public void run() {
                        bondAndConnect();
                    }
                }.start();
            }
        });

//        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext)
//                .setView(mLayout)
//                .setCancelable(true);
//        scanDialog = builder.create();
//        scanDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialogInterface) {
//                Log.d(TAG, "scanDialog dismiss");
//                if (mBluetoothAdapter.isDiscovering()) {
//                    mBluetoothAdapter.cancelDiscovery();
//                }
//            }
//        });
        //开始搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        mBluetoothAdapter.startDiscovery();
    }

    /**
     * 显示蓝牙绑定列表
     */
    @SuppressLint("MissingPermission")
    public void getBondList() {
        if (mBluetoothAdapter == null) {
            showTip("当前设备不支持蓝牙功能！");
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            showTip("当前蓝牙未打开");
            return;
        }

        Set<BluetoothDevice> bondList = mBluetoothAdapter.getBondedDevices();
        final List<BluetoothDevice> list = new ArrayList<>(bondList);
        String[] deviceNameList = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            deviceNameList[i] = list.get(i).getName();
        }

        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
        android.app.AlertDialog dialog = builder.setTitle("选择要连接的蓝牙绑定设备")
                .setSingleChoiceItems(deviceNameList, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mCurDevice = list.get(which);
                        new Thread() {
                            @Override
                            public void run() {
                                bondAndConnect();
                            }
                        }.start();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    /**
     * 蓝牙配对并连接
     */
    @SuppressLint("MissingPermission")
    public void bondAndConnect() {
        //取消搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        if (mCurDevice == null) {
            showToast("远程蓝牙设备为空！");
            return;
        }
        //当前蓝牙设备未配对，则先进行配对
        if (mCurDevice.getBondState() == BluetoothDevice.BOND_NONE) {
            Log.d(TAG, "create bond to " + mCurDevice.getName());
            boolean nRet = BluetoothUtil.createBond(mCurDevice);
            if (!nRet) {
                showToast("createBond fail！");
                return;
            }
            showLoadingDialog("正在与【" + mCurDevice.getName() + "】进行配对...");
            mFlag = 0;
            while (mFlag == 0) {
                SystemClock.sleep(250);
            }
            if (mFlag == -1) {
                showToast("与【" + mCurDevice.getName() + "】的蓝牙配对失败");
                dismissLoadingDialog();
                return;
            }
        }

        // 连接
        if (mCurDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
            //设置
            Intent intent = new Intent(DeviceBluetoothListActivity.this, DeviceBluetoothInfoActivity.class);
            intent.putExtra("mCurDevice", mCurDevice);
            //跳转到蓝牙详细页
            startActivity(intent);

//            showLoadingDialog("正在与【" + mCurDevice.getName() + "】进行连接...");
//            try {
//                //创建Socket
//                BluetoothSocket socket = mCurDevice.createRfcommSocketToServiceRecord(GlobalDef.BT_UUID);
//                //启动连接线程
//                socket.connect();
//                mThread = new DeviceBluetoothListActivity.SocketThread(socket);
//                mThread.start();
//                showToast(("成功与【" + mCurDevice.getName() + "】建立连接"));
//
//                // 数据发送测试
////                sendData();
//                dismissLoadingDialog();
//                // 弹窗
//                showBluetoothInfo();
//
//            } catch (IOException e) {
//                Log.d(TAG, "socket connect fail");
//                showToast(("连接【" + mCurDevice.getName() + "】失败"));
//                e.printStackTrace();
//            }
        }
        dismissLoadingDialog();
    }

    /**
     * 显示设备详细信息
     */
//    public void showBluetoothInfo() {
//        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
//        View mLayout = layoutInflater.inflate(R.layout.device_bluetooth_info_view, null);
//
//        txt_msg_bluetooth = mLayout.findViewById(R.id.txt_msg_bluetooth);
//
//        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext)
//                .setView(mLayout)
//                .setCancelable(true);
//        Looper.prepare();
//        deviceDialog = builder.create();
//
//        //显示对话框
//        deviceDialog.show();
//
//        Window window = deviceDialog.getWindow();
//        int width = getResources().getDisplayMetrics().widthPixels;
//        int height = getResources().getDisplayMetrics().heightPixels;
//        window.setLayout(width - 80, height * 4 / 5);
//
//        deviceDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                disconnect();
//            }
//        });
//        Looper.loop();
//    }

//    /**
//     * 断开连接
//     */
//    public void disconnect() {
//        if (mThread == null || mThread.isConnected() == false) {
//            showToast("未存在蓝牙连接");
//            return;
//        }
//
//        try {
//            if (mThread != null) {
//                mThread.release();
//                mThread = null;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 将编辑框内的数据发送给服务端
//     */
//    public void sendData() {
//        if (mThread == null || mThread.isConnected() == false) {
//            showTip("蓝牙socket未连接");
//            return;
//        }
//
////        final String strData = edtData.getText().toString();
//        final String strData = "发送测试";
//        if (strData == null || strData.trim().equals("")) {
//            showTip("编辑框不能为空!");
//            return;
//        }
//
//        try {
//            byte[] bData = null;
//            if (mCurDataType == DATATYPE_STR) {
//                bData = strData.getBytes();
//            } else {
//                bData = StringUtil.hexStringToBytes(strData);
//            }
//
//            if (bData == null) {
//                showTip("编辑框内的数据不符合要求!");
//                return;
//            }
//
//            if (mThread != null) {
//                mThread.writeData(bData, 0, bData.length);
//                showToast("数据发送成功");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            showToast("数据发送出现异常!");
//        }
//    }
//
//
//    /**
//     * socket线程类
//     */
//    class SocketThread extends Thread {
//        private BluetoothSocket mSocket = null;
//        private InputStream mIn;
//        private OutputStream mOut;
//        private boolean isOpen = false;
//        private byte[] mRecBuffer = new byte[1024 * 10];
//        private int mRecPos = 0;
//
//        public SocketThread(BluetoothSocket socket) {
//            try {
//                mSocket = socket;
//                mIn = mSocket.getInputStream();
//                mOut = mSocket.getOutputStream();
//                isOpen = true;
//                Log.d(TAG, "a socket thread create");
//            } catch (IOException e) {
//                e.printStackTrace();
//                Log.e(TAG, "create SocketThread fail");
//            }
//        }
//
//        @Override
//        public void run() {
//            int readLen = 0;
//            byte[] buffer = new byte[1024];
//            try {
//                while (isOpen) {
//                    readLen = mIn.read(buffer);
//                    if (readLen > 0) {
//                        System.arraycopy(buffer, 0, mRecBuffer, mRecPos, readLen);
//                        mRecPos += readLen;
//
//                        while (true) {
//                            if (mIn.available() > 0) {//若流中有数据，则读取
//                                readLen = mIn.read(buffer);
//                                if ((mRecPos + readLen) > mRecBuffer.length) {//超出缓冲区
//                                    showTip("读取数据超出缓冲区，将已读取的数据输出：");
//                                    showTip("Receive hex data = " + StringUtil.bytesToHexString(mRecBuffer, 0, mRecPos));
//                                    showTip("Receive string data = " + new String(mRecBuffer, 0, mRecPos).trim());
//                                    mRecPos = 0;
//                                    Arrays.fill(mRecBuffer, (byte) 0x00);
//                                }
//
//                                System.arraycopy(buffer, 0, mRecBuffer, mRecPos, readLen);
//                                mRecPos += readLen;
//                            } else {//若流中无数据
//                                if (mRecPos > 0) {//说明此时数据读取完毕，将内容输出
//                                    showTip("Receive hex data = " + StringUtil.bytesToHexString(mRecBuffer, 0, mRecPos));
//                                    showToast("Receive string data = " + new String(mRecBuffer, 0, mRecPos).trim());
//                                    Log.i("socket", "Receive string data = " + new String(mRecBuffer, 0, mRecPos).trim());
//
//
//                                    //更新界面数据
//                                    //txt_msg_bluetooth.setText(new String(mRecBuffer, 0, mRecPos).trim());
//
//                                    mRecPos = 0;
//                                    Arrays.fill(mRecBuffer, (byte) 0x00);
//                                }
//                                break;
//                            }
//                        }
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                release();
//            }
//        }
//
//        /**
//         * 是否连接成功
//         *
//         * @return
//         */
//        public boolean isConnected() {
//            if (isOpen && mSocket != null) {
//                return true;
//            }
//            return false;
//        }
//
//        /**
//         * 释放
//         */
//        public void release() {
//            Log.d(TAG, "A socketThread release");
//            try {
//                if (isOpen) {
//                    showToast("与蓝牙服务端的连接已断开");
//                }
//                isOpen = false;
//
//                if (mOut != null) {
//                    try {
//                        mOut.close();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    mOut = null;
//                }
//                if (mIn != null) {
//                    try {
//                        mIn.close();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    mIn = null;
//                }
//                if (mSocket != null) {
//                    try {
//                        mSocket.close();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    mSocket = null;
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//
//        /**
//         * 写入数据
//         *
//         * @param data
//         * @param offset
//         * @param len
//         */
//        public void writeData(byte[] data, int offset, int len) {
//            if (data == null || offset < 0 || len <= 0 || (len + offset) > data.length) {
//                Log.e(TAG, "BT writeData params fail");
//                return;
//            }
//
//            try {
//                byte[] buffer = new byte[1024];
//                int nPos = offset;
//                while ((nPos - offset) < len) {
//                    Arrays.fill(buffer, (byte) 0x00);
//                    if ((len + offset - nPos) >= buffer.length) {
//                        System.arraycopy(data, nPos, buffer, 0, buffer.length);
//                        mOut.write(buffer);
//                        nPos += buffer.length;
//
//                    } else {
//                        int last = len + offset - nPos;
//                        System.arraycopy(data, nPos, buffer, 0, last);
//                        mOut.write(buffer, 0, last);
//                        nPos += last;
//                    }
//                }
//                mOut.flush();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 蓝牙广播接收器
     */
    class BluetoothBroadcastReceiver extends BroadcastReceiver {
        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "Action received is " + action);
            //蓝牙搜索
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice scanDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (scanDevice == null || scanDevice.getName() == null) {
                    return;
                }

                int btType = scanDevice.getType();
                if (btType == BluetoothDevice.DEVICE_TYPE_LE || btType == BluetoothDevice.DEVICE_TYPE_UNKNOWN) {
                    return;
                }

                Log.d(TAG, "bt name=" + scanDevice.getName() + " address=" + scanDevice.getAddress());
                deviceList.add(scanDevice);
                short rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);
                rssiList.add(rssi);
                listViewBluetoothAdapter.notifyDataSetChanged();
            }
            //蓝牙配对
            else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (mCurDevice != null && btDevice.getAddress().equals(mCurDevice.getAddress())) {
                    int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
                    if (state == BluetoothDevice.BOND_NONE) {
                        showToast("已取消与设备" + btDevice.getName() + "的配对");
                        mFlag = -1;
                    } else if (state == BluetoothDevice.BOND_BONDED) {
                        showToast("与设备" + btDevice.getName() + "配对成功");
                        mFlag = 1;
                    }
                }
            } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState) {
                    case BluetoothAdapter.STATE_TURNING_ON:
                        Log.i(TAG, "onReceive---------STATE_TURNING_ON");
                        break;
                    case BluetoothAdapter.STATE_ON:
                        Log.i(TAG, "onReceive---------STATE_ON");
                        showToast("蓝牙当前状态：ON");
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        Log.i(TAG, "onReceive---------STATE_TURNING_OFF");
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        Log.i(TAG, "onReceive---------STATE_OFF");
                        showToast("蓝牙当前状态：OFF");
                        break;
                }
            }
        }
    }

    /**
     * 申请权限的结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(this, permissions, grantResults, mPermissionsListener, false);
    }

//    public void openActivity(String activityName){
//        Intent intent=new Intent();
//        intent.setClassName(MainActivity.this,activityName);
//        startActivity(intent);
//    }

    /**
     * 权限申请回调
     */
    private PermissionUtil.OnPermissionsListener mPermissionsListener = new PermissionUtil.OnPermissionsListener() {

        @Override
        public void onPermissionsOwned() {

        }

        @Override
        public void onPermissionsForbidden(String[] permissions, int[] grantResults, ArrayList<String> pmList) {
            Set<String> nameSet = PermissionUtil.getPermissionsNameByChinese(pmList.toArray(new String[0]));
            if (nameSet != null && nameSet.size() > 0) {
                AlertDialog dialog = new AlertDialog.Builder(mContext)
                        .setTitle("警告")
                        .setMessage("请前往设置中手动授予" + nameSet.toString() + "权限，否则功能无法正常运行！")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 一般情况下如果用户不授权的话，功能是无法运行的，做退出处理
                                finish();
                            }
                        })
                        .create();
                dialog.show();
            }
        }

        @Override
        public void onPermissionsDenied(String[] permissions, int[] grantResults, ArrayList<String> pmList) {
            Set<String> nameSet = PermissionUtil.getPermissionsNameByChinese(pmList.toArray(new String[0]));
            if (nameSet != null && nameSet.size() > 0) {
                //重新请求权限
                AlertDialog dialog = new AlertDialog.Builder(mContext)
                        .setTitle("提示")
                        .setMessage(nameSet.toString() + "权限为应用必要权限，请授权")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String[] sList = pmList.toArray(new String[0]);
                                //重新申请权限,通过权限名的方式申请多组权限
                                PermissionUtil.requestByPermissionName((Activity) mContext, sList, 10000, mPermissionsListener);
                            }
                        })
                        .create();
                dialog.show();
            }
        }

        @Override
        public void onPermissionsSucceed() {

        }
    };

    /**
     * 初始化下拉刷新
     */
    private void initRefreshLayout() {
        //下拉刷新
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout_bluetooth);
        //监听刷新状态
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //提示消息
                showToast("正在刷新");
                //扫描设备
                scanBluetooth();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

}
